<?php

namespace App\Http\Controllers;

use App\Http\Models\AircraftModel;
use App\Http\Models\Airport;
use App\Http\Models\Cabin;
use App\Http\Models\Flight;
use App\Http\Models\OnFlight;
use App\Http\Models\TicketType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OnFlightController extends Controller
{
	/**
	 * Display a listing of the resource.
	 *
	 * @param Request $request
	 * @return  \Illuminate\Http\JsonResponse
	 */
	public function index(Request $request)
	{
		DB::enableQueryLog();
		if ($request->has('limit')) {
			if ($request->has('flight_id')) {
				$items = OnFlight::where('flight_id', $request->input('flight_id'))->paginate($request->input('limit'));
			} else {
				$items = OnFlight::join('flights', function ($join) {
					$join->on('on_flights.flight_id', '=', 'flights.id');
				})
					->select('on_flights.id', 'flight_id', 'execution_price', 'current_status', 'estimated_takeoff_time', 'actual_takeoff_time', 'estimated_arrival_time', 'actual_arrival_time', 'boarding_gate', 'flight_no', 'start_terminal_id', 'end_terminal_id')
					->where(function ($query) use ($request) {
						if (!empty($request['start_terminal_id'])) {
							$query->where('start_terminal_id', $request->input('start_terminal_id'));
						}

						if (!empty($request['end_terminal_id'])) {
							$query->where('end_terminal_id', $request->input('end_terminal_id'));
						}

						if (!empty($request['flight_no'])) {
							$query->where('flight_no', 'like', '%' . $request->input('flight_no') . '%');
						}
					})
					->paginate($request->input('limit'));
			}

		} else {
			$items = OnFlight::all();
		}

		return $this->table($items, DB::getQueryLog());
	}
/**
	 * Display a listing of the resource.
	 *
	 * @param Request $request
	 * @return  \Illuminate\Http\JsonResponse
	 */
	public function query(Request $request)
	{
		DB::enableQueryLog();
		if ($request->has('limit')) {
			$items = OnFlight::leftJoin('flights', function ($join) {$join->on('on_flights.flight_id', '=', 'flights.id');})
				->select('on_flights.id', 'flight_id', 'execution_price', 'current_status', 'estimated_takeoff_time', 'actual_takeoff_time', 'estimated_arrival_time', 'actual_arrival_time', 'boarding_gate', 'flight_no', 'start_terminal_id', 'end_terminal_id', 'model_id', 'pricing')
				->where(function ($query) use ($request) {
					if($request->has('flight_no')){
						$query->where('flight_no', 'like', '%' . $request->input('flight_no') . '%');
					}else{
						$query->whereIn('start_terminal_id', function($query) use ($request) {
							$query->select('terminals.id')
								->from('terminals')->join('airports', 'terminals.airport_id', '=', 'airports.id')
								->where('airports.city_id', $request->input('start_city_id'));
						});
						$query->whereIn('end_terminal_id', function($query) use ($request) {
							$query->select('terminals.id')
								->from('terminals')->join('airports', 'terminals.airport_id', '=', 'airports.id')
								->where('airports.city_id', $request->input('end_city_id'));
						});
					}
					$query->where(DB::Raw("TO_DAYS(on_flights.estimated_takeoff_time)"), '=', DB::Raw("TO_DAYS('".$request->input('date')."')"));
				})
				->paginate($request->input('limit'));
		}

		$cabins = Cabin::all();
		$cabinMap = [];
		foreach ($cabins as $c){
			$cabinMap[$c['id']] = $c['cabin_class'];
		}

		$atArr = Airport::with(['terminals'])->get();
		$atMap = [];
		foreach ($atArr as $a) {
			foreach ($a['terminals'] as $t) {
				$atMap[$t['id']]=$a['name'].$t['name'];
			}
		}

		foreach ($items->items() as $o){
			$o['model_name'] = AircraftModel::find($o['model_id'])['name'];

			$ticketTypes = TicketType::where('on_flight_id', $o['id'])->get();
			foreach ($ticketTypes as $t){
				$t['cabin'] = $cabinMap[$t['cabin_id']];
			}
			$o['ticketTypes']=$ticketTypes;
			$o['start_airport'] = $atMap[$o['start_terminal_id']];
			$o['end_airport'] = $atMap[$o['end_terminal_id']];
		}

		return $this->table($items, DB::getQueryLog());
	}
/*
select ticketTypeID,
			 onFlightID,
			 cabinClass cabin,
			 basicPrice,
			 discount,
			 ticketCount,
			 remainingTickets,
			 luggageLimit,
			 changeWithdrawalRules
from tickettype t left join cabin c on t.cabinID = c.cabinID
where onFlightID = #{onFlightID}
*/

	/**
	 * Store a newly created resource in storage.
	 *
	 * @param \Illuminate\Http\Request $request
	 * @return  \Illuminate\Http\JsonResponse
	 */
	public function store(Request $request)
	{
		$model = new OnFlight;
		foreach ($request->toArray() as $key => $value) {
			if (in_array($key, $model->getFillable())) {
				$model[$key] = $value;
			}
		}
		return $model->save() ?
			$this->success('') : $this->failed('添加失败');
	}

	/**
	 * Display the specified resource.
	 *
	 * @param int $id
	 * @return  \Illuminate\Http\JsonResponse
	 */
	public function show($id)
	{
		return $this->success(OnFlight::find($id));
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param \Illuminate\Http\Request $request
	 * @param int $id
	 * @return  \Illuminate\Http\JsonResponse
	 */
	public function update(Request $request, $id)
	{
		$model = OnFlight::find($id);
		foreach ($request->toArray() as $key => $value) {
			if (in_array($key, $model->getFillable())) {
				$model[$key] = $value;
			}
		}
		return $model->update() ? $this->success('') : $this->failed('更新失败');
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param int $id
	 * @return  \Illuminate\Http\JsonResponse
	 */
	public function destroy($id)
	{
		return OnFlight::where('id', $id)->delete() ? $this->success('') : $this->failed('删除失败');

	}
}
